package com.sample.aa.graf_v25;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.Date;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.impl.client.DefaultHttpClient;

import android.annotation.TargetApi;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Toast;

@TargetApi(14)
public class MainActivity extends Activity {
	Board board;

	public static int H;
	public static int W;
	public static boolean IS_CHANGE = false;
	public static Paint paint;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		board = new Board(this);
		setContentView(board);
		board.requestFocus();

		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);

		H = metrics.heightPixels;
		W = metrics.widthPixels;

	}

	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
		super.onSaveInstanceState(savedInstanceState);
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.settings, menu);
		return true;
	}

	public void exit() {
		finish();
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.blue_title:
			board.setColor(Color.BLUE);
			return true;

		case R.id.green_title:
			board.setColor(Color.GREEN);
			return true;

		case R.id.red_title:
			board.setColor(Color.RED);
			return true;

		case R.id.pink_title:
			board.setColor(Color.MAGENTA);
			return true;

		case R.id.yellow_title:
			board.setColor(Color.YELLOW);
			return true;

		case R.id.black_title:
			board.setColor(Color.BLACK);
			return true;
		case R.id.save_file:
			saveImage(board);
			board.clear();
			return true;
		case R.id.send_server:
			Log.i("send server ", "send");
			sendImage(board);
			board.clear();
			return true;
		case R.id.reset:
			board.clear();
			return true;
		}
		return false;
	}

	public void saveImage(Board board) {

		board.setDrawingCacheEnabled(true);
		board.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);

		Bitmap bitmap = board.getDrawingCache();
		String path = Environment.getExternalStorageDirectory()
				.getAbsolutePath();

		File directory = new File(path + "/Graf_App/");

		if (!directory.exists()) {
			directory.mkdirs();
		}
		File file = new File(directory, getFileName() + ".png");

		Log.i("file ", file.getPath());

		FileOutputStream ostream;
		try {
			file.canWrite();
			file.canRead();
			file.canExecute();
			file.createNewFile();
			ostream = new FileOutputStream(file);
			bitmap.compress(CompressFormat.PNG, 100, ostream);
			ostream.flush();
			ostream.close();
			Toast.makeText(getApplicationContext(), "image saved", 5000).show();
			board.destroyDrawingCache();
		} catch (Exception e) {
			Log.e("exception", e.toString());
			Toast.makeText(getApplicationContext(), "error", 5000).show();
		}
	}

	public void onDestroy() {
		super.onDestroy();
	}

	private String getFileName() {
		Date currentDate = new Date(System.currentTimeMillis());
		return currentDate.toString().replace(" ", "_").replace(":", "");
	}

	private void sendImage(Board board) {

		try {
			
			board.setDrawingCacheEnabled(true);
			board.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
			Log.i("board", board.toString());
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			Bitmap bitmap = board.getDrawingCache();
			Log.i("bitmap", bitmap.toString());
			bitmap.compress(CompressFormat.JPEG, 75, bos);
			byte[] data = bos.toByteArray();
			HttpClient httpClient = new DefaultHttpClient();
			Log.i("httpClient", httpClient.toString());
			HttpPost postRequest = new HttpPost(
					"http://192.168.204.1:8080/RESTImgDown/rest/file/upload");
			ByteArrayBody bab = new ByteArrayBody(data, getFileName() + ".jpg");
			Log.i("ByteArrayBody bab", bab.toString());
			MultipartEntity reqEntity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			reqEntity.addPart("uploadedFile", bab);

			postRequest.setEntity(reqEntity);
			Log.i("MultipartEntity reqEntity", reqEntity.toString());
			
			
			Log.i("postRequest ", postRequest.toString());
			
			HttpResponse response = httpClient.execute(postRequest);
			Log.i("response", response.toString());
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent(), "UTF-8"));
			String sResponse;
			StringBuilder s = new StringBuilder();

			while ((sResponse = reader.readLine()) != null) {
				s = s.append(sResponse);
			}
			Log.i("response", "Response: " + s);
			Toast.makeText(getApplicationContext(), "image sent", 5000).show();
			board.destroyDrawingCache();
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "error", 5000).show();
			Log.e("exception", e.toString());
		}

	}

}